<?php

namespace tmcore\services\wechat;

use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\MiniApp\Application;
use tmcore\exceptions\WeChatException;

/**
 * 小程序服务类
 */
class WxApService
{
    protected $app;

    /**
     * @var array
     */
    protected $config;

    /**
     * 初始化
     */
    public function __construct()
    {
        $this->config = $this->getConfig();
        $this->app = new Application($this->config);
    }

    /**
     * 获取实例
     * @return Application
     */
    public function getApplication() {
        return $this->app;
    }

    /**
     * 获取配置
     * @return array
     * @throws WeChatException
     */
    protected function getConfig()
    {
        $config = WxConfigService::getMnpConfig();
        if (empty($config['app_id']) || empty($config['secret'])) {
            throw new WeChatException('请先设置微信小程序配置');
        }
        return $config;
    }


    /**
     * 根据code获取微信信息
     * @param string $code
     * @return array
     * @throws WeChatException
     */
    public function getApInfoByCode($code)
    {
        try {
            return $this->app->getUtils()->codeToSession($code);
        } catch (HttpException $e) {
            throw new WeChatException($e->getMessage());
        }
    }

    /**
     * 解密微信小程序数据
     * @param string $session_key
     * @param string $iv
     * @param string $encryptedData
     * @return array
     */
    public function decryptApData($session_key, $iv, $encryptedData): array
    {
        return $this->app->getUtils()->decryptSession($session_key, $iv, $encryptedData);
    }

    /**
     * 获取手机号
     * @param string $code
     * @return array
     * @throws HttpException
     */
    public function getUserPhoneNumber(string $code)
    {
        return $this->app->getUtils()->getPhoneNumber($code);
    }
}